package pl.edu.agh.bd2.util;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateDAO <T> {
	private Session session;
	private Transaction trans;
	
	public void persist(T item){
		session = HibernateUtil.getSessionFactory().openSession();
		
		try{
			trans = session.beginTransaction();
			session.persist(item);			
			trans.commit();
		}
		catch(Exception e){
			e.printStackTrace();
			if(trans == null)
				trans.rollback();			
		}		
	}
	
	public void saveOrUpdate(T item){
		session = HibernateUtil.getSessionFactory().openSession();
		
		try{
			trans = session.beginTransaction();
			session.saveOrUpdate(item);			
			trans.commit();
		}
		catch(Exception e){
			e.printStackTrace();
			if(trans == null)
				trans.rollback();			
		}		
	}
	
	public void delete(T item){
		session = HibernateUtil.getSessionFactory().openSession();
		
		try{
			trans = session.beginTransaction();
			session.delete(item);			
			trans.commit();
		}
		catch(Exception e){
			e.printStackTrace();
			if(trans == null)
				trans.rollback();			
		}		
	}	
	
	public void update(T item){
		session = HibernateUtil.getSessionFactory().openSession();
		
		try{
			trans = session.beginTransaction();
			session.update(item);				
			trans.commit();
		}
		catch(Exception e){
			e.printStackTrace();
			if(trans == null)
				trans.rollback();			
		}		
	}	
	

	public List<T> get(String type){
		session = HibernateUtil.getSessionFactory().openSession();
		List<T> list = null;
		
		try{
			trans = session.beginTransaction();
			list = (List<T>)session.createQuery("from " + type).list();
						
		}
		catch(Exception e){
			e.printStackTrace();
			if(trans == null)
				trans.rollback();			
		}
		
		return list;
	}	
}
